#include <gtest/gtest.h>
#include "nlohmann/json.hpp"

#include <string>
#include <regex>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <atomic>
#include <algorithm>

using json = nlohmann::json;

// --- 函数 ---

std::string getCurrentTimestampISO8601() {
    auto now = std::chrono::system_clock::now();
    auto itt = std::chrono::system_clock::to_time_t(now);
    std::ostringstream ss;
    ss << std::put_time(std::gmtime(&itt), "%Y-%m-%dT%H:%M:%SZ");
    return ss.str();
}

void initializeNextId(const json& tasks_data, std::atomic<int>& next_id) {
    int max_id = 0;
    if (tasks_data.is_array()) {
        for (const auto& task : tasks_data) {
            if (task.contains("id") && task["id"].is_number_integer()) {
                max_id = std::max(max_id, task["id"].get<int>());
            }
        }
    }
    next_id = max_id + 1;
}

// --- 测试用例 ---

TEST(TaskUtilsTest, GetCurrentTimestampISO8601Format) {
    std::string timestamp = getCurrentTimestampISO8601();
    std::regex iso8601_regex("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z");
    EXPECT_TRUE(std::regex_match(timestamp, iso8601_regex))
        << "时间戳 '" << timestamp << "' 不符合预期的 ISO 8601 UTC 格式 (YYYY-MM-DDTHH:MM:SSZ)";
}

TEST(TaskUtilsTest, InitializeNextIdLogic) {
    // 场景 1: 空数组
    std::atomic<int> next_id1(1);
    json empty_tasks = json::array();
    initializeNextId(empty_tasks, next_id1);
    EXPECT_EQ(next_id1.load(), 1);

    // 场景 2: 包含 ID 的数组
    std::atomic<int> next_id2(1);
    json tasks_with_ids = json::parse(R"([
        {"id": 5, "title": "任务 5"},
        {"id": 2, "title": "任务 2"},
        {"id": 8, "title": "任务 8"}
    ])");
    initializeNextId(tasks_with_ids, next_id2);
    EXPECT_EQ(next_id2.load(), 9);

    // 场景 3: 混合 ID
    std::atomic<int> next_id3(1);
    json tasks_mixed = json::parse(R"([
        {"id": 3, "title": "任务 3"},
        {"title": "没有 ID 的任务"},
        {"id": "not_an_int", "title": "ID 不是整数的任务"},
        {"id": 7, "title": "任务 7"}
    ])");
    initializeNextId(tasks_mixed, next_id3);
    EXPECT_EQ(next_id3.load(), 8);

    // 场景 4: 非数组
    std::atomic<int> next_id4(99);
    json not_an_array = json::object({{"key", "value"}});
    initializeNextId(not_an_array, next_id4);
    EXPECT_EQ(next_id4.load(), 1);


    // 场景 5: 负数 ID
    std::atomic<int> next_id5(1);
    json tasks_with_negative_ids = json::parse(R"([
        {"id": -5, "title": "负数 ID 任务"},
        {"id": 2, "title": "任务 2"}
    ])");
    initializeNextId(tasks_with_negative_ids, next_id5);
    EXPECT_EQ(next_id5.load(), 3);

    // 场景 6: 全部无效 ID
    std::atomic<int> next_id6(1);
    json tasks_all_invalid = json::parse(R"([
        {"title": "没有 ID"},
        {"id": "abc", "title": "字符串 ID"}
    ])");
    initializeNextId(tasks_all_invalid, next_id6);
    EXPECT_EQ(next_id6.load(), 1);
}
